import { createRouter, createWebHistory } from 'vue-router'
import auth from '@/store/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('../views/Layout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'process/definitions',
          name: 'ProcessDefinitions',
          component: () => import('../views/process/Definitions.vue')
        },
        {
          path: 'process/start',
          name: 'ProcessStartList',
          component: () => import('@/views/process/StartList.vue'),
          meta: { 
            title: '发起流程',
            requiresAuth: true
          }
        },
        {
          path: 'process/start/:processKey',
          name: 'ProcessStart',
          component: () => import('@/views/process/Start.vue'),
          meta: { 
            title: '发起流程',
            requiresAuth: true
          },
          props: true
        },
        {
          path: 'process/tasks',
          name: 'TaskList',
          component: () => import('../views/process/TaskList.vue')
        },
        {
          path: 'process/my-requests',
          name: 'MyRequests',
          component: () => import('../views/process/MyRequests.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    localStorage.setItem('redirectPath', to.fullPath)
  }

  if (to.matched.some(record => record.meta.requiresAuth !== false)) {
    if (!auth.isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else if (to.path === '/login' && auth.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router 